<template>
  <a-config-provider :theme="antdTheme">
    <div class="h-full flex flex-col bg-gray-50 dark:bg-dark-950">
    <!-- Header -->
    <div class="bg-white dark:bg-dark-900 shadow-sm border-b border-gray-200 dark:border-dark-700 p-6 flex-shrink-0">
      <div class="flex items-center justify-between">
        <div>
            <h1 class="text-2xl font-bold text-gray-900 dark:text-gray-100">
              {{ menuInfo?.name || '数据管理' }}
            </h1>
          <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
            {{ menuInfo?.description || `管理 ${tableName} 表数据` }}
          </p>
        </div>
          <div class="flex items-center space-x-3">
            <a-button 
              v-if="hasPermission('create')"
              @click="showCreateModal" 
              type="primary"
             class="flex items-center space-x-2"
            ><template #icon>
              <PlusIcon class="w-4 h-4" />
            </template>
              新增数据
            </a-button>
            <a-button 
            @click="refreshData" 
              :loading="loading"
              class="flex items-center space-x-2"
              ><template #icon>
              <ArrowPathIcon class="w-4 h-4" />
            </template>
          
            刷新
            </a-button>
        </div>
      </div>
    </div>

      <!-- 搜索和筛选区域 -->
    <div class="bg-white dark:bg-dark-900 p-4 border-b border-gray-200 dark:border-dark-700 flex-shrink-0">
        <div class="flex items-center gap-4 flex-wrap">
        <!-- 搜索框 -->
          <div class="flex-1 min-w-[300px]">
            <a-input-search
              v-model:value="searchQuery"
              placeholder="搜索数据..."
              allow-clear
              enter-button="搜索"
              @search="handleSearch"
              :loading="loading"
              size="middle"
            />
          </div>
          
          <!-- 日期筛选 -->
          <a-range-picker
            v-model:value="dateRange"
            @change="handleDateRangeChange"
            :placeholder="['开始日期', '结束日期']"
            format="YYYY-MM-DD"
            size="middle"
            style="width: 240px"
          />
          
          <!-- 状态筛选 -->
          <a-select
            v-model:value="statusFilter"
            placeholder="状态筛选"
            allow-clear
            @change="handleFilterChange"
            size="middle"
            style="width: 120px"
          >
            <a-select-option value="active">启用</a-select-option>
            <a-select-option value="inactive">禁用</a-select-option>
            <a-select-option value="pending">待审核</a-select-option>
          </a-select>
          
          <!-- 每页显示数量 -->
          <a-select 
            v-model:value="pagination.pageSize" 
            @change="handlePageSizeChange"
            size="middle"
            style="width: 100px"
          >
            <a-select-option :value="10">10条</a-select-option>
            <a-select-option :value="20">20条</a-select-option>
            <a-select-option :value="50">50条</a-select-option>
            <a-select-option :value="100">100条</a-select-option>
          </a-select>
          
          <!-- 重置按钮 -->
          <a-button @click="resetFilters" size="middle">
            重置筛选
          </a-button>
      </div>
    </div>

      <!-- 主表格区域 - 自适应高度 -->
      <div class="flex-1 flex flex-col overflow-hidden bg-white dark:bg-dark-900">
      <!-- Loading -->
        <div v-if="loading && tableData.length === 0" class="flex items-center justify-center flex-1">
          <a-spin size="large">
            <template #indicator>
              <div class="loading-spinner w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full"></div>
            </template>
            <div class="mt-4 text-gray-600 dark:text-gray-400">加载中...</div>
          </a-spin>
      </div>

      <!-- Error State -->
        <div v-else-if="error" class="flex items-center justify-center flex-1">
        <div class="text-center">
            <a-result
              status="error"
              :title="error"
              sub-title="请检查网络连接或联系管理员"
            >
              <template #extra>
                <a-button type="primary" @click="loadData">
                  重新加载
                </a-button>
              </template>
            </a-result>
        </div>
      </div>

        <!-- Data Table -->
        <div v-else class="flex-1 overflow-hidden">
            <a-table
            :columns="antdColumns"
              :data-source="tableData"
              :pagination="false"
              :loading="loading"
            :row-key="(record: any) => record.id"
            :scroll="{ x: 'max-content', y: 'calc(100vh - 300px)' }"
            size="middle"
            :row-selection="hasPermission('delete') ? rowSelection : null"
            class="dynamic-table h-full"
          >
            <!-- 自定义列渲染 -->
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.dataIndex === 'status'">
                <a-tag :color="getStatusColor(text)">
                  {{ getStatusText(text) }}
                </a-tag>
              </template>
              
              <template v-else-if="column.key === 'actionList'">
                <a-space>
                  <a-tooltip title="查看详情" v-if="hasPermission('read')">
                    <a-button 
                      type="text" 
                      size="small"
                      @click="viewRecord(record)"
                      :icon="h(EyeIcon)"
                    />
                  </a-tooltip>
                  
                  <a-tooltip title="编辑" v-if="hasPermission('update')">
                    <a-button 
                      type="text" 
                      size="small"
                      @click="editRecord(record)"
                      :icon="h(PencilIcon)"
                    />
                  </a-tooltip>
                  
                  <a-tooltip title="删除" v-if="hasPermission('delete')">
                    <a-popconfirm
                      title="确定要删除这条记录吗？"
                      ok-text="确定"
                      cancel-text="取消"
                      @confirm="deleteRecord(record)"
                    >
                      <a-button 
                        type="text" 
                        size="small"
                        danger
                        :icon="h(TrashIcon)"
                      />
                    </a-popconfirm>
                  </a-tooltip>
                </a-space>
              </template>
              
              <template v-else-if="isDateField(column.dataIndex)">
                <span>{{ formatDate(text) }}</span>
              </template>
              </template>
            </a-table>
        </div>
      </div>

      <!-- 底部分页 -->
      <div v-if="pagination.total > 0" class="bg-white dark:bg-dark-900 px-6 py-4 border-t border-gray-200 dark:border-dark-700 flex-shrink-0">
        <div class="flex items-center justify-between">
          <!-- 批量操作信息 -->
          <div class="flex items-center space-x-4">
            <span v-if="selectedRowKeys.length > 0" class="text-sm text-blue-600 dark:text-blue-400">
              已选择 {{ selectedRowKeys.length }} 项
              <a-button 
                v-if="hasPermission('delete')"
                type="link" 
                size="small" 
                danger
                @click="batchDelete"
                :loading="batchDeleteLoading"
              >
                批量删除
              </a-button>
              <a-button type="link" size="small" @click="clearSelection">
                清除选择
              </a-button>
            </span>
            <span v-else class="text-sm text-gray-500 dark:text-gray-400">
              共 {{ pagination.total }} 条记录
            </span>
          </div>
          
          <!-- 分页组件 -->
          <a-pagination
            v-model:current="pagination.current"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :show-size-changer="false"
            :show-quick-jumper="true"
            :show-total="(total: any, range: any) => `显示 ${range[0]}-${range[1]} 条，共 ${total} 条`"
            @change="handlePaginationChange"
            size="small"
          />
      </div>
    </div>

      <!-- 新增/编辑弹窗 -->
      <a-modal
        v-model:open="showFormModal"
        :title="formMode === 'create' ? '新增记录' : '编辑记录'"
        width="800px"
        :confirm-loading="formLoading"
        @ok="handleFormSubmit"
        @cancel="cancelForm"
        destroy-on-close
      >
        <a-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          layout="vertical"
          v-if="showFormModal"
        >
          <a-row :gutter="16">
            <a-col 
              v-for="column in editableColumns" 
              :key="column.field"
              :span="getFormColSpan(column)"
            >
              <a-form-item 
                :label="column.title"
                :name="column.field"
                :required="column.required"
              >
                <!-- 文本输入 -->
                <a-input
                  v-if="column.type === 'string'"
                  v-model:value="formData[column.field]"
                  :placeholder="`请输入${column.title}`"
                />
                
                <!-- 大文本输入 -->
                <a-textarea
                  v-else-if="column.type === 'text'"
                  v-model:value="formData[column.field]"
                  :placeholder="`请输入${column.title}`"
                  :rows="4"
                />
                
                <!-- 数字输入 -->
                <a-input-number
                  v-else-if="column.type === 'number'"
                  v-model:value="formData[column.field]"
                  :placeholder="`请输入${column.title}`"
                  style="width: 100%"
                />
                
                <!-- 日期选择 -->
                <a-date-picker
                  v-else-if="column.type === 'date'"
                  v-model:value="formData[column.field]"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                />
                
                <!-- 邮箱输入 -->
                <a-input
                  v-else-if="column.type === 'email'"
                  v-model:value="formData[column.field]"
                  :placeholder="`请输入${column.title}`"
                  type="email"
                />
                
                <!-- 状态选择 -->
                <a-select
                  v-else-if="column.field === 'status'"
                  v-model:value="formData[column.field]"
                  :placeholder="`请选择${column.title}`"
                >
                  <a-select-option value="active">启用</a-select-option>
                  <a-select-option value="inactive">禁用</a-select-option>
                  <a-select-option value="pending">待审核</a-select-option>
                </a-select>
                
                <!-- 默认文本输入 -->
                <a-input
                  v-else
                  v-model:value="formData[column.field]"
                  :placeholder="`请输入${column.title}`"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-modal>

      <!-- 查看详情弹窗 -->
      <a-modal
        v-model:open="showDetailModal"
        title="查看详情"
        width="900px"
        :footer="null"
      >
        <a-descriptions 
          v-if="selectedRecord"
          :column="2"
          bordered
          size="middle"
        >
          <a-descriptions-item 
            v-for="column in visibleColumns" 
            :key="column.field"
            :label="column.title"
            :span="getDescriptionSpan(column)"
          >
            <template v-if="column.field === 'status'">
              <a-tag :color="getStatusColor(selectedRecord[column.field])">
                {{ getStatusText(selectedRecord[column.field]) }}
              </a-tag>
            </template>
            <template v-else-if="isDateField(column.field)">
              {{ formatDate(selectedRecord[column.field]) }}
            </template>
            <template v-else>
              {{ formatCellValue(selectedRecord[column.field], column.type) }}
            </template>
          </a-descriptions-item>
        </a-descriptions>
      </a-modal>
    </div>
  </a-config-provider>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch, h } from 'vue'
import { useRoute } from 'vue-router'
import { dynamicMenuAPI } from '@/api'
import { useMenuStore } from '@/store/menu'
import { useAuthStore } from '@/store/auth'
import { useThemeStore } from '@/store/theme'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { message, theme } from 'ant-design-vue'
import type { TableColumnsType } from 'ant-design-vue'
import dayjs, { type Dayjs } from 'dayjs'

// Icons
import {
  ArrowPathIcon,
  EyeIcon,
  PencilIcon,
  TrashIcon,
  PlusIcon
} from '@heroicons/vue/24/outline'

// Stores
const route = useRoute()
const menuStore = useMenuStore()
const authStore = useAuthStore()
const themeStore = useThemeStore()

// 基础状态
const tableName = ref<string>('')
const menuKey = ref<string>('')
const menuInfo = ref<any>(null)
const loading = ref(false)
const error = ref<string | null>(null)
const tableData = ref<any[]>([])
const tableColumns = ref<any[]>([])
const selectedRecord = ref<any>(null)

// 搜索和筛选
const searchQuery = ref('')
const dateRange = ref<[Dayjs, Dayjs] | null>(null)
const statusFilter = ref<string | undefined>(undefined)

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: false,
  showQuickJumper: true,
  showTotal: (total: any, range: any) => 
    `显示 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
})

// 表格选择
const selectedRowKeys = ref<string[]>([])
const batchDeleteLoading = ref(false)

// 弹窗状态
const showFormModal = ref(false)
const showDetailModal = ref(false)
const formMode = ref<'create' | 'edit'>('create')
const formLoading = ref(false)
const formData = ref<any>({})
const formRef = ref()

// 权限检查 - 根据实际权限数据优化
const hasPermission = (action: string): boolean => {
  if (!tableName.value) return false
  
  // 获取用户权限
  const userPermissions = authStore.userPermissions || []
  
  // 如果用户有系统管理权限，直接通过
  if (userPermissions.includes('system:manage')) {
    return true
  }
  
  // 根据表名构建权限检查
  const resourceName = getResourceName(tableName.value)
  const possiblePermissions = [
    `${resourceName}:${action}`,     // 例如: product:read, customer:create
    `table:${action}`,               // 通用表权限
    `${tableName.value}:${action}`,  // 直接表名权限
    `*:${action}`,                   // 通配符权限
    '*'                              // 超级权限
  ]
  
  const hasPermission = possiblePermissions.some(perm => userPermissions.includes(perm))
  if (hasPermission) return true
  
  // 检查菜单级别的权限（作为补充检查）
  if (menuInfo.value?.permissions && menuInfo.value.permissions.length > 0) {
    return menuInfo.value.permissions.includes(action)
  }
  
  // 如果没有菜单配置或没有权限要求，默认允许
  return true
}

// 根据表名获取资源名称
const getResourceName = (tableName: string): string => {
  const tableMap: Record<string, string> = {
    'products': 'product',
    'customers': 'customer', 
    'orders': 'order',
    'users': 'user',
    'roles': 'role',
    'inventory': 'inventory',
    'permissions': 'permission',
    'table_configs': 'system',
    'table_themes': 'system',
    'table_actions': 'system',
    'table_columns': 'system',
    'chat_histories': 'chat',
    'ai_sql_logs': 'system',
    'dynamic_menus': 'system',
    'user_roles': 'user',
    'role_permissions': 'role',
    'inventory_logs': 'inventory'
  }
  return tableMap[tableName] || tableName
}

// 行选择配置
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: string[]) => {
    selectedRowKeys.value = keys
  },
  getCheckboxProps: (_record: any) => ({
    disabled: !hasPermission('delete')
  })
}))

// Ant Design Vue 主题配置
const antdTheme = computed(() => ({
  algorithm: themeStore.isDark ? theme.darkAlgorithm : theme.defaultAlgorithm,
  token: {
    colorPrimary: themeStore.config.primaryColor,
    colorInfo: themeStore.config.accentColor,
    colorBgContainer: themeStore.isDark ? '#1f2937' : '#ffffff',
    colorBgElevated: themeStore.isDark ? '#374151' : '#ffffff',
    colorText: themeStore.isDark ? '#f9fafb' : '#111827',
    colorTextSecondary: themeStore.isDark ? '#d1d5db' : '#6b7280',
    colorBorder: themeStore.isDark ? '#4b5563' : '#d1d5db',
    borderRadius: 6,
    colorFillAlter: themeStore.isDark ? '#374151' : '#fafafa',
    colorFillContent: themeStore.isDark ? '#4b5563' : '#f5f5f5',
    colorBgContainerDisabled: themeStore.isDark ? '#374151' : '#f5f5f5'
  }
}))

// 计算表格列配置
const antdColumns = computed((): TableColumnsType => {
  if (!visibleColumns.value.length) return []
  
  const columns: any[] = visibleColumns.value.map(column => ({
    title: column.title,
    dataIndex: column.field,
    key: column.field,
    width: getColumnWidth(column),
    sorter: column.sortable !== false,
    ellipsis: true
  }))
  
  // 添加操作列
  if (hasPermission('read') || hasPermission('update') || hasPermission('delete')) {
    columns.push({
      title: '操作',
      key: 'actionList',
      width: 120,
      fixed: 'right'
    })
  }
  
  return columns
})

// 可见列
const visibleColumns = computed(() => {
  return tableColumns.value.filter(col => 
    col.field !== 'id' && 
    col.field !== 'password' && 
    col.field !== 'deleted_at'
  )
})

// 可编辑列
const editableColumns = computed(() => {
  return visibleColumns.value.filter(col => 
    col.field !== 'created_at' && 
    col.field !== 'updated_at' &&
    col.field !== 'id'
  )
})

// 表单验证规则
const formRules = computed(() => {
  const rules: any = {}
  
  editableColumns.value.forEach(column => {
    if (column.required) {
      rules[column.field] = [
        { required: true, message: `请输入${column.title}`, trigger: 'blur' }
      ]
    }
    
    if (column.type === 'email') {
      rules[column.field] = [
        ...(rules[column.field] || []),
        { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
      ]
    }
  })
  
  return rules
})

// 工具方法
const getColumnWidth = (column: any): number => {
  if (column.type === 'text') return 200
  if (isDateField(column.field)) return 160
  if (column.field === 'status') return 100
  if (column.field === 'id') return 80
  return 150
}

const isDateField = (fieldName: string): boolean => {
  if (!fieldName) return false
  return fieldName.includes('_at') || 
         fieldName.includes('date') ||
         fieldName.includes('time') ||
         fieldName.includes('created') ||
         fieldName.includes('updated')
}

const getFormColSpan = (column: any): number => {
  if (column.type === 'text') return 24
  return 12
}

const getDescriptionSpan = (column: any): number => {
  if (column.type === 'text') return 2
  return 1
}

const getStatusColor = (status: string): string => {
  const colorMap: Record<string, string> = {
    'active': 'green',
    'inactive': 'red', 
    'pending': 'orange',
    'approved': 'blue',
    'rejected': 'red',
    '1': 'green',
    '0': 'red'
  }
  return colorMap[status] || 'default'
}

const getStatusText = (status: string): string => {
  const textMap: Record<string, string> = {
    'active': '启用',
    'inactive': '禁用',
    'pending': '待审核', 
    'approved': '已审核',
    'rejected': '已拒绝',
    '1': '启用',
    '0': '禁用'
  }
  return textMap[status] || status
}

const formatDate = (dateStr: string): string => {
  if (!dateStr) return '-'
  try {
    return format(new Date(dateStr), 'yyyy-MM-dd HH:mm:ss', { locale: zhCN })
  } catch {
    return dateStr
  }
}

const formatCellValue = (value: any, type?: string): string => {
  if (value === null || value === undefined) return '-'
  
  if (type?.includes('date') || type?.includes('time')) {
    return formatDate(value)
  }
  
  if (typeof value === 'object') {
    return JSON.stringify(value)
  }
  
  return String(value)
}

// 数据加载方法
const loadData = async () => {
  if (!tableName.value) {
    error.value = '无效的表名'
    return
  }

  loading.value = true
  error.value = null

  try {
    const params: any = {
      page: pagination.current,
      limit: pagination.pageSize,
      search: searchQuery.value
    }
    
    // 添加日期范围筛选
    if (dateRange.value) {
      params.start_date = dateRange.value[0].format('YYYY-MM-DD')
      params.end_date = dateRange.value[1].format('YYYY-MM-DD')
    }
    
    // 添加状态筛选
    if (statusFilter.value) {
      params.status = statusFilter.value
    }

    const response = await dynamicMenuAPI.getTableData(tableName.value, params)

    if (response.success && response.data) {
      tableData.value = response.data.list || []
      
      // 更新分页信息
      if (response.data.pagination) {
        Object.assign(pagination, response.data.pagination)
      }
      
      // 如果还没有列信息，获取表结构
      if (tableColumns.value.length === 0 && tableData.value.length > 0) {
        await loadTableStructure()
      }
    } else {
      throw new Error(response.message || '获取数据失败')
    }
  } catch (err: any) {
    console.error('加载表数据失败:', err)
    error.value = err.message || '网络错误，请稍后重试'
    message.error(error.value)
  } finally {
    loading.value = false
  }
}

const loadTableStructure = async () => {
  try {
    const response = await dynamicMenuAPI.getTableStructure(tableName.value)
    if (response.success && response.data) {
      tableColumns.value = response.data.columns.map((col: any) => ({
        field: col.field,
        title: formatColumnTitle(col.field),
        type: mapColumnType(col.type),
        required: !col.null && col.default === null,
        sortable: true
      }))
    }
  } catch (err) {
    console.error('获取表结构失败:', err)
    // 如果获取结构失败，使用数据的键作为列
    if (tableData.value.length > 0) {
      const firstRow = tableData.value[0]
      tableColumns.value = Object.keys(firstRow).map(key => ({
        field: key,
        title: formatColumnTitle(key),
        type: 'string',
        required: false,
        sortable: true
      }))
    }
  }
}

const formatColumnTitle = (fieldName: string): string => {
  const nameMap: Record<string, string> = {
    'id': 'ID',
    'created_at': '创建时间',
    'updated_at': '更新时间',
    'user_id': '用户ID',
    'username': '用户名',
    'email': '邮箱',
    'name': '名称',
    'title': '标题',
    'description': '描述',
    'status': '状态',
    'phone': '电话',
    'address': '地址',
    'price': '价格',
    'category_id': '分类ID',
    'stock': '库存',
    'sku': 'SKU'
  }
  
  return nameMap[fieldName] || fieldName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
}

const mapColumnType = (dbType: string): string => {
  const type = dbType.toLowerCase()
  if (type.includes('int') || type.includes('decimal') || type.includes('float') || type.includes('double')) {
    return 'number'
  }
  if (type.includes('date') || type.includes('time')) {
    return 'date'
  }
  if (type.includes('text') || type.includes('longtext')) {
    return 'text'
  }
  if (type.includes('email')) {
    return 'email'
  }
  return 'string'
}

// 事件处理方法
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleFilterChange = () => {
  pagination.current = 1
  loadData()
}

const handleDateRangeChange = () => {
  pagination.current = 1
  loadData()
}

const handlePageSizeChange = () => {
  pagination.current = 1
  loadData()
}

const handlePaginationChange = (page: number) => {
  pagination.current = page
  loadData()
}

const refreshData = () => {
  pagination.current = 1
  selectedRowKeys.value = []
  loadData()
}

const resetFilters = () => {
  searchQuery.value = ''
  dateRange.value = null
  statusFilter.value = undefined
  pagination.current = 1
  loadData()
}

const clearSelection = () => {
  selectedRowKeys.value = []
}

// CRUD 操作
const showCreateModal = () => {
  formMode.value = 'create'
  formData.value = {}
  showFormModal.value = true
}

const viewRecord = (record: any) => {
  selectedRecord.value = record
  showDetailModal.value = true
}

const editRecord = (record: any) => {
  formMode.value = 'edit'
  formData.value = { ...record }
  
  // 转换日期字段
  editableColumns.value.forEach(column => {
    if (column.type === 'date' && formData.value[column.field]) {
      formData.value[column.field] = dayjs(formData.value[column.field])
    }
  })
  
  showFormModal.value = true
}

const deleteRecord = async (record: any) => {
  try {
    await dynamicMenuAPI.deleteRecord(tableName.value, record.id)
    message.success('删除成功')
    await loadData()
  } catch (err: any) {
    console.error('删除失败:', err)
    message.error(err.message || '删除失败')
  }
}

const batchDelete = async () => {
  try {
    batchDeleteLoading.value = true
    
    const deletePromises = selectedRowKeys.value.map(id => 
      dynamicMenuAPI.deleteRecord(tableName.value, parseInt(id))
    )
    
    await Promise.all(deletePromises)
    message.success(`成功删除 ${selectedRowKeys.value.length} 条记录`)
    selectedRowKeys.value = []
    await loadData()
  } catch (err: any) {
    console.error('批量删除失败:', err)
    message.error(err.message || '批量删除失败')
  } finally {
    batchDeleteLoading.value = false
  }
}

const handleFormSubmit = async () => {
  try {
    await formRef.value.validate()
    formLoading.value = true
    
    // 处理表单数据
    const submitData = { ...formData.value }
    
    // 转换日期字段
    editableColumns.value.forEach(column => {
      if (column.type === 'date' && submitData[column.field]) {
        submitData[column.field] = submitData[column.field].format('YYYY-MM-DD')
      }
    })
    
    // 使用动态表格API进行CRUD操作
    if (formMode.value === 'create') {
      await dynamicMenuAPI.createRecord(tableName.value, submitData)
      message.success('创建成功')
    } else {
      await dynamicMenuAPI.updateRecord(tableName.value, submitData.id, submitData)
      message.success('更新成功')
    }
    
    showFormModal.value = false
    await loadData()
  } catch (err: any) {
    console.error('保存失败:', err)
    message.error(err.message || '保存失败')
  } finally {
    formLoading.value = false
  }
}

const cancelForm = () => {
  showFormModal.value = false
  formData.value = {}
  formRef.value?.resetFields()
}

// 初始化
const initialize = () => {
  // 清理之前的状态
  tableData.value = []
  tableColumns.value = []
  error.value = null
  loading.value = false
  selectedRecord.value = null
  showFormModal.value = false
  showDetailModal.value = false
  searchQuery.value = ''
  selectedRowKeys.value = []
  
  // 重置分页
  pagination.current = 1
  pagination.total = 0
  
  // 设置新的参数
  tableName.value = route.query.table as string || ''
  menuKey.value = route.query.menu as string || ''
  
  if (menuKey.value) {
    menuInfo.value = menuStore.getMenuByKey(menuKey.value)
  }
  
  if (tableName.value) {
    loadData()
  } else {
    error.value = '请选择有效的数据表'
  }
}

// 监听路由变化
watch(() => route.query, (newQuery, oldQuery) => {
  const newTable = newQuery?.table
  const newMenu = newQuery?.menu
  const oldTable = oldQuery?.table
  const oldMenu = oldQuery?.menu
  
  if (newTable !== oldTable || newMenu !== oldMenu) {
    initialize()
  }
}, { immediate: true })

onMounted(() => {
  initialize()
})
</script>

<style scoped>
/* 自定义滚动条 */
:deep(.ant-table-body) {
  scrollbar-width: thin;
  scrollbar-color: rgb(156, 163, 175) transparent;
}

:deep(.ant-table-body::-webkit-scrollbar) {
  width: 6px;
  height: 6px;
}

:deep(.ant-table-body::-webkit-scrollbar-track) {
  background: transparent;
}

:deep(.ant-table-body::-webkit-scrollbar-thumb) {
  background: rgb(156, 163, 175);
  border-radius: 3px;
}

:deep(.ant-table-body::-webkit-scrollbar-thumb:hover) {
  background: rgb(107, 114, 128);
}

/* 表格动画 */
:deep(.ant-table-tbody > tr) {
  transition: all 0.2s ease;
}

/* Loading动画 */
.loading-spinner {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 自定义表格样式 */
.dynamic-table {
  height: 100%;
}

:deep(.dynamic-table .ant-table-container) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.dynamic-table .ant-table-body) {
  flex: 1;
  overflow: auto;
}
</style>